package com.haoniu.web.controller.module;

import com.haoniu.common.support.Convert;
import com.haoniu.common.utils.http.HttpUtils;
import com.haoniu.common.utils.huanxin.HuanXinConstants;
import com.haoniu.common.utils.huanxin.HuanXinUtils;
import com.haoniu.module.domain.database.*;
import com.haoniu.module.domain.dto.*;
import com.haoniu.module.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.haoniu.common.annotation.Log;
import com.haoniu.common.enums.BusinessType;
import com.haoniu.web.core.base.BaseController;
import com.haoniu.framework.web.page.TableDataInfo;
import com.haoniu.common.base.AjaxResult;

import javax.annotation.Resource;
import java.util.*;

/**
 * 房间 信息操作处理
 *
 * @author houyijun
 * @date 2019-01-24
 */
@Controller
@RequestMapping("/module/room")
public class RoomController extends BaseController {
    private String prefix = "module/room";
    private final static Logger logger = LoggerFactory.getLogger(RoomController.class);
    @Autowired
    private RoomService roomService;
    @Resource
    private RoomLeiService roomLeiService;
    @Resource
    private UserService userService;
    @Resource
    private RoomUserService roomUserService;
    @Resource
    private UserWalletService userWalletService;
    @Resource
    private UserInviteRoomService userInviteRoomService;
    @Resource
    private UserInviteService userInviteService;


    @RequiresPermissions("module:room:view")
    @GetMapping()
    public String room() {
        return prefix + "/room";
    }

    /**
     * 查询房间列表
     */
    @RequiresPermissions("module:room:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Room room) {
        startPage();
        List<Room> list = roomService.selectRoomList(room);
        return getDataTable(list);
    }

    /**
     * 新增房间
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        List<User> ordinaryList = userService.findAllOrdinary();
        mmap.put("ordinaryList", ordinaryList);
        return prefix + "/add";
    }

    /**
     * 新增保存房间
     */
    @RequiresPermissions("module:room:add")
    @Log(title = "房间", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RoomTypeDTO roomTypeDTO) {

        Integer roleId = getUser().getUserId().intValue();
        //单雷
        if (roomTypeDTO.getRedType().equals("1")) {
            Room room = new Room();
            room.setName(roomTypeDTO.getName());
            room.setUserId(roleId);
            room.setType(roomTypeDTO.getRoomType());
            Integer roomBossId = roomTypeDTO.getRoomBossId();
            if(roomBossId==null){
                roomTypeDTO.setRoomBossId(1);
            }
            //房间密码
            room.setPassword(roomTypeDTO.getPassword());
            if (!"".equals(roomTypeDTO.getPassword())) {
                //判断是否有密码，有密码为1
                room.setIsPassword(1);
            } else {
                room.setIsPassword(0);
            }

            //群主id
            room.setRoomBossId(roomTypeDTO.getRoomBossId());
            //将该用户设置成群主
            userService.setUpRoomBoss(roomTypeDTO.getRoomBossId());

            //房间编号
            String randomStr = "";
            for (int i = 0; i < 6; i++) {
                int num = (int) (Math.random() * 10);
                randomStr = randomStr + num;
            }
            room.setRoomNumber(randomStr);

            //群
            // String huanXinGroupId = HuanXinUtils.addGroup("1", room.getName(), null);
            //聊天室
            String huanXinGroupId = HuanXinUtils.addRoom("1", room.getName(), null);

            room.setHuanxinGroupId(huanXinGroupId);
            //创建群 加入群头像（群主头像）
            room.setRoomImg(HuanXinConstants.DEFAULT_PHOTO);
            room.setCreateTime(new Date());
            roomService.insertRoom(room);

            Room roomAdd = roomService.selectRoomByHxId(room.getHuanxinGroupId());

            //创建房间时 群主在房间里
            RoomUser roomUser = new RoomUser();
            roomUser.setUserId(roomTypeDTO.getRoomBossId());
            roomUser.setRoomId(roomAdd.getId());
            roomUser.setUserRank(0);
            roomUserService.insertRoomUser(roomUser);

            //查询群主所有的下级
            UserInvite userInvite = new UserInvite();
            userInvite.setUserId(roomTypeDTO.getRoomBossId());
            List<Integer> userInviteList = userInviteService.selectUserInviteList(userInvite);
            if (userInviteList.size() != 0) {
                //将群主加入房间表
                UserInviteRoom uir = new UserInviteRoom();
                uir.setRoomId(roomAdd.getId());
                uir.setUserId(roomTypeDTO.getRoomBossId());
                userInviteRoomService.insertUserInviteRoomMapper(uir);

                //添加邀请用户房间表
                for (int i = 0; i < userInviteList.size(); i++) {
                    UserInviteRoom userInviteRoom = new UserInviteRoom();
                    userInviteRoom.setRoomId(roomAdd.getId());
                    userInviteRoom.setUserId(userInviteList.get(i));
                    userInviteRoomService.insertUserInviteRoomMapper(userInviteRoom);
                }
            }

            //环信添加群主进入群组
            //HuanXinUtils.addUserToGroup(roomTypeDTO.getRoomBossId() + "", room.getHuanxinGroupId());

            //环信添加群主进入聊天室
            HuanXinUtils.addUserToRoom(roomTypeDTO.getRoomBossId() + "", room.getHuanxinGroupId());

            RoomLei roomLei = new RoomLei();
            roomLei.setRoomId(roomAdd.getId());
            roomLei.setType(roomTypeDTO.getRedType());
            roomLei.setAmount(roomTypeDTO.getOddAmount());
            roomLei.setMoneyMax(roomTypeDTO.getOddMoneyMax());
            roomLei.setMoneyMin(roomTypeDTO.getOddMoneyMin());
            roomLei.setOneLei(roomTypeDTO.getOddOneLei());

            return toAjax(roomLeiService.insertRoomLei(roomLei));

            //多雷
        } else if (roomTypeDTO.getRedType().equals("2")) {
            Room room = new Room();
            room.setName(roomTypeDTO.getName());
            room.setUserId(roleId);
            room.setType(roomTypeDTO.getRoomType());
            Integer roomBossId = roomTypeDTO.getRoomBossId();
            if(roomBossId==null){
                roomTypeDTO.setRoomBossId(1);
            }
            //房间密码
            room.setPassword(roomTypeDTO.getPassword());

            if (!"".equals(roomTypeDTO.getPassword())) {
                //判断是否有密码，有密码为1
                room.setIsPassword(1);
            } else {
                room.setIsPassword(0);
            }

            //群主id
            room.setRoomBossId(roomTypeDTO.getRoomBossId());

            //将该用户设置成群主
            userService.setUpRoomBoss(roomTypeDTO.getRoomBossId());

            //房间编号
            String randomStr = "";
            for (int i = 0; i < 6; i++) {
                int num = (int) (Math.random() * 10);
                randomStr = randomStr + num;
            }
            room.setRoomNumber(randomStr);

            String huanXinGroupId = HuanXinUtils.addRoom("1", room.getName(), null);

            room.setHuanxinGroupId(huanXinGroupId);
            //创建群 加入群头像（群主头像）
            room.setRoomImg(HuanXinConstants.DEFAULT_PHOTO);
            room.setCreateTime(new Date());
            roomService.insertRoom(room);

            Room roomAdd = roomService.selectRoomByHxId(room.getHuanxinGroupId());

            //创建房间时 群主在房间里
            RoomUser roomUser = new RoomUser();
            roomUser.setUserId(roomTypeDTO.getRoomBossId());
            roomUser.setRoomId(roomAdd.getId());
            roomUser.setUserRank(0);
            roomUserService.insertRoomUser(roomUser);

            //查询群主所有的下级
            UserInvite userInvite = new UserInvite();
            userInvite.setUserId(roomTypeDTO.getRoomBossId());
            List<Integer> userInviteList = userInviteService.selectUserInviteList(userInvite);
            if (userInviteList.size() != 0) {
                //将群主加入房间表
                UserInviteRoom uir = new UserInviteRoom();
                uir.setRoomId(roomAdd.getId());
                uir.setUserId(roomTypeDTO.getRoomBossId());
                userInviteRoomService.insertUserInviteRoomMapper(uir);

                //添加邀请用户房间表
                for (int i = 0; i < userInviteList.size(); i++) {
                    UserInviteRoom userInviteRoom = new UserInviteRoom();
                    userInviteRoom.setRoomId(roomAdd.getId());
                    userInviteRoom.setUserId(userInviteList.get(i));
                    userInviteRoomService.insertUserInviteRoomMapper(userInviteRoom);
                }
            }

            //环信添加群主进入聊天室
            HuanXinUtils.addUserToRoom(roomBossId + "", room.getHuanxinGroupId());

            RoomLei roomLeiDan = new RoomLei();
            roomLeiDan.setRoomId(roomAdd.getId());
            roomLeiDan.setType("1");
            roomLeiDan.setAmount(roomTypeDTO.getOddAmount());
            roomLeiDan.setMoneyMax(roomTypeDTO.getOddMoneyMax());
            roomLeiDan.setMoneyMin(roomTypeDTO.getOddMoneyMin());
            roomLeiDan.setOneLei(roomTypeDTO.getOddOneLei());
            roomLeiService.insertRoomLei(roomLeiDan);

            RoomLei roomLeiDuo = new RoomLei();
            roomLeiDuo.setRoomId(roomAdd.getId());
            roomLeiDuo.setType(roomTypeDTO.getRedType());
            roomLeiDuo.setAmount(roomTypeDTO.getEvenAmount());
            roomLeiDuo.setMoneyMax(roomTypeDTO.getEvenMoneyMax());
            roomLeiDuo.setMoneyMin(roomTypeDTO.getEvenMoneyMin());
            roomLeiDuo.setOneLei(roomTypeDTO.getOneLei());
            roomLeiDuo.setTwoLei(roomTypeDTO.getTwoLei());
            roomLeiDuo.setThreeLei(roomTypeDTO.getThreeLei());
            roomLeiDuo.setFourLei(roomTypeDTO.getFourLei());
            roomLeiDuo.setFiveLei(roomTypeDTO.getFiveLei());
            roomLeiDuo.setSixLei(roomTypeDTO.getSixLei());
            roomLeiDuo.setSevenLei(roomTypeDTO.getSevenLei());
            roomLeiDuo.setEightLei(roomTypeDTO.getEightLei());
            roomLeiDuo.setNineLei(roomTypeDTO.getNineLei());

            return toAjax(roomLeiService.insertRoomLei(roomLeiDuo));
        }

        return toAjax(-1);
    }

    /**
     * 修改房间
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {

        List<RoomViewDTO> roomLei = roomLeiService.getRoomById(id);
        RoomTypeDTO roomTypeDTO = new RoomTypeDTO();
        for (RoomViewDTO lei : roomLei) {
            if (lei.getRedType().equals("2")) {
                roomTypeDTO.setName(lei.getName());
                roomTypeDTO.setRedType("多雷");
                roomTypeDTO.setRoomType(lei.getRoomType());
                roomTypeDTO.setEvenAmount(lei.getAmount());
                roomTypeDTO.setEvenMoneyMax(lei.getMoneyMax());
                roomTypeDTO.setEvenMoneyMin(lei.getMoneyMin());
                roomTypeDTO.setTwoLei(lei.getTwoLei());
                roomTypeDTO.setOneLei(lei.getOneLei());
                roomTypeDTO.setThreeLei(lei.getThreeLei());
                roomTypeDTO.setFourLei(lei.getFourLei());
                roomTypeDTO.setFiveLei(lei.getFiveLei());
                roomTypeDTO.setSixLei(lei.getSixLei());
                roomTypeDTO.setSevenLei(lei.getSevenLei());
                roomTypeDTO.setEightLei(lei.getEightLei());
                roomTypeDTO.setNineLei(lei.getNineLei());
                roomTypeDTO.setPassword(lei.getPassword());

                if (!"".equals(lei.getPassword())) {
                    //判断是否有密码，有密码为1
                    roomTypeDTO.setIsPassword(1);
                } else {
                    roomTypeDTO.setIsPassword(0);
                }
            }
            if (lei.getRedType().equals("1")) {
                roomTypeDTO.setName(lei.getName());
                roomTypeDTO.setRoomType(lei.getRoomType());
                roomTypeDTO.setOddMoneyMax(lei.getMoneyMax());
                roomTypeDTO.setOddAmount(lei.getAmount());
                roomTypeDTO.setOddMoneyMin(lei.getMoneyMin());
                roomTypeDTO.setOddOneLei(lei.getOneLei());
                roomTypeDTO.setPassword(lei.getPassword());

                if (!"".equals(lei.getPassword())) {
                    //判断是否有密码，有密码为1
                    roomTypeDTO.setIsPassword(1);
                } else {
                    roomTypeDTO.setIsPassword(0);
                }
            }
        }
        mmap.put("roomId", id);
        mmap.put("roomTypeDTO", roomTypeDTO);

        return prefix + "/edit";
    }

    /**
     * 修改保存房间
     */
    @RequiresPermissions("module:room:edit")
    @Log(title = "房间", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RoomTypeDTO roomTypeDTO, Integer roomId) {
        RoomLei oddRoom = roomLeiService.getRoomByIdAndType(roomId, 1);
        oddRoom.setAmount(roomTypeDTO.getOddAmount());
        oddRoom.setMoneyMax(roomTypeDTO.getOddMoneyMax());
        oddRoom.setMoneyMin(roomTypeDTO.getOddMoneyMin());
        oddRoom.setOneLei(roomTypeDTO.getOddOneLei());
        oddRoom.setUpdateTime(new Date());
        roomLeiService.updateRoomLei(oddRoom);

        if (null != roomTypeDTO.getEvenAmount() && !roomTypeDTO.getEvenAmount().equals("")) {
            RoomLei evenRoom = roomLeiService.getRoomByIdAndType(roomId, 2);
            evenRoom.setAmount(roomTypeDTO.getEvenAmount());
            evenRoom.setMoneyMin(roomTypeDTO.getEvenMoneyMin());
            evenRoom.setMoneyMax(roomTypeDTO.getEvenMoneyMax());
            evenRoom.setOneLei(roomTypeDTO.getOneLei());
            evenRoom.setTwoLei(roomTypeDTO.getTwoLei());
            evenRoom.setThreeLei(roomTypeDTO.getThreeLei());
            evenRoom.setFourLei(roomTypeDTO.getFourLei());
            evenRoom.setFiveLei(roomTypeDTO.getFiveLei());
            evenRoom.setSixLei(roomTypeDTO.getSixLei());
            evenRoom.setSevenLei(roomTypeDTO.getSevenLei());
            evenRoom.setEightLei(roomTypeDTO.getEightLei());
            evenRoom.setNineLei(roomTypeDTO.getNineLei());
            evenRoom.setUpdateTime(new Date());
            roomLeiService.updateRoomLei(evenRoom);
        }

        Room room = roomService.selectRoomById(roomId);
        room.setName(roomTypeDTO.getName());
        room.setUpdateTime(new Date());
        room.setPassword(roomTypeDTO.getPassword());
        //room.setRoomBossId(roomTypeDTO.getRoomBossId());

        if (!"".equals(roomTypeDTO.getPassword())) {
            //判断是否有密码，有密码为1
            room.setIsPassword(1);
        } else {
            room.setIsPassword(0);
        }
        return toAjax(roomService.updateRoom(room));
    }

    /**
     * 删除房间
     */
    @RequiresPermissions("module:room:remove")
    @Log(title = "房间", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] idStrs = Convert.toStrArray(ids);

        if (idStrs.length == 0) {
            return toAjax(-1);
        }
        //循环删除房间环信
        for (int i = 0; i < idStrs.length; i++) {
            Room room = new Room();
            //删除邀请用户房间关系
            userInviteRoomService.deleteUserInviteRoomMapper(new Integer(idStrs[i]));

            room = roomService.selectRoomById(new Integer(idStrs[i]));
            List<Integer> roomBossIdList = roomService.findRoomBossId(new Integer(idStrs[i]));
            if (roomBossIdList.size() == 0) {
                return toAjax(-1);
            }
            for (i = 0; i < roomBossIdList.size(); i++) {
                //将群主设置成普通用户
                userService.setUpOrdinary(roomBossIdList.get(i));
            }

            // HuanXinUtils.deleteGroup(room.getHuanxinGroupId());
            HuanXinUtils.deleteRoom(room.getHuanxinGroupId());
        }
        return toAjax(roomService.deleteRoomByIds(ids));
    }


    /**
     * 房间会员
     */
    @RequiresPermissions("module:room:roomVip")
    @GetMapping("/roomVip/{roomId}")
    public String userDetailMoneyList(@PathVariable("roomId") Integer roomId, ModelMap mmap) {
        mmap.put("roomId", roomId);
        return "module/room/roomVip";
    }


    /**
     * 房间会员
     *
     * @return
     */
    @RequiresPermissions("module:room:vipList")
    @PostMapping("/vipList")
    @ResponseBody
    public TableDataInfo vipList(RoomVipDTO roomVipDTO) {
        startPage();
        Map<String, Object> map = new HashMap<>();
        map.put("roomId", roomVipDTO.getRoomId());
        List<RoomVipDTO> list = roomService.getRoomVipList(map);
        return getDataTable(list);
    }


    /**
     * 跳转添加界面
     */
    @GetMapping("/toAddRoomRobot")
    public String toAddRoomRobot(Integer id, ModelMap mmap) {
        //订单id
        mmap.put("roomId", id);
        List<RoomViewDTO> roomLei = roomLeiService.getRoomById(id);
        RoomTypeDTO roomTypeDTO = new RoomTypeDTO();
        for (RoomViewDTO lei : roomLei) {
            if (lei.getRedType().equals("2")) {
                roomTypeDTO.setName(lei.getName());
                roomTypeDTO.setRedType("多雷");
                roomTypeDTO.setRoomType(lei.getRoomType());
                roomTypeDTO.setEvenAmount(lei.getAmount());
                roomTypeDTO.setEvenMoneyMax(lei.getMoneyMax());
                roomTypeDTO.setEvenMoneyMin(lei.getMoneyMin());
                roomTypeDTO.setOneLei(lei.getOneLei());
                roomTypeDTO.setTwoLei(lei.getTwoLei());
                roomTypeDTO.setThreeLei(lei.getThreeLei());
                roomTypeDTO.setFourLei(lei.getFourLei());
                roomTypeDTO.setFiveLei(lei.getFiveLei());
                roomTypeDTO.setSixLei(lei.getSixLei());
                roomTypeDTO.setSevenLei(lei.getSevenLei());
                roomTypeDTO.setEightLei(lei.getEightLei());
                roomTypeDTO.setNineLei(lei.getNineLei());
            }
            if (lei.getRedType().equals("1")) {
                roomTypeDTO.setName(lei.getName());
                roomTypeDTO.setRoomType(lei.getRoomType());
                roomTypeDTO.setOddAmount(lei.getAmount());
                roomTypeDTO.setOddMoneyMax(lei.getMoneyMax());
                roomTypeDTO.setOddMoneyMin(lei.getMoneyMin());
                roomTypeDTO.setOddOneLei(lei.getOneLei());
            }
        }

        mmap.put("roomTypeDTO", roomTypeDTO);

        return prefix + "/addRoomRobot";
    }

    /**
     * 新增保存机器人
     */
    @RequiresPermissions("module:room:addRoomRobot")
    @Log(title = "房间", businessType = BusinessType.INSERT)
    @PostMapping("/addRoomRobot")
    @ResponseBody
    public AjaxResult addRoomRobot(RoomRobotDTO roomRobotDTO) {
        User user1 = userService.selectUserByPhone(roomRobotDTO.getPhone());
        if (null != user1) {
            return error("用户已存在");
        }
        User name = userService.selectUserByNickName(roomRobotDTO.getNickName());
        if (null != name) {
            return AjaxResult.error("已存在用户");
        }

        User roomRobot = new User();
        roomRobot.setNickName(roomRobotDTO.getNickName());
        roomRobot.setPhone(roomRobotDTO.getPhone());
        roomRobot.setLeiType(roomRobotDTO.getLeiType());
        roomRobot.setUserType(roomRobotDTO.getUserType());
        roomRobot.setRobotType(roomRobotDTO.getRobotType());
        //添加机器人默认头像
        roomRobot.setHeadImg("/upload/img/default_avatar.png");
        userService.insertUser(roomRobot);

        User user = userService.selectUserByPhone(roomRobot.getPhone());
        user.setInviteCode("000" + user.getId());
        userService.updateUser(user);

        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(user.getId());
        userWallet.setCreateTime(new Date());
        userWalletService.insertUserWallet(userWallet);

        RoomUser roomUser = new RoomUser();
        roomUser.setRoomId(roomRobotDTO.getRoomId());
        roomUser.setUserId(user.getId());
        roomUser.setUserRank(10);

        return toAjax(roomUserService.insertRoomUser(roomUser));
    }

    @Value("${send.packet.url}")
    private String sendPacketUrl;

    /**
     * 开启或关闭自动发包
     */
    @Log(title = "开启或关闭自动发包", businessType = BusinessType.OTHER)
    @PostMapping("/onOffSendPacket")
    @ResponseBody
    public AjaxResult onOffSendPacket(Integer type) {
        String s = HttpUtils.sendGet(sendPacketUrl, "type=" + type);
        System.out.println(s);
        return success();
    }
}
